import Objects from '../utils/Objects'

/**
 * 初始化景观
 */
export default function mixinLandscape(Incident) {
  Incident.prototype.setObjects = function (objectArray) {
    this.$objects = this.createObjects(objectArray)
  }

  /**
   * 初始化景观
   * Landscape: 景观
   */
  Incident.prototype.initLandscape = function() {
    const self = this

    this.lanes = this.createLanes()
    this.dividers = this.lanes.dividers
    this.lines = this.lanes.lines
    this.linesPlane = this.lanes.linesPlane
    this.scene.add(this.lanes)

    this.timeArrow = this.createTimeArrow()
    this.scene.add(this.timeArrow)

    this.timeArrow.tick = function() {
      this.position.z = self.camera.position.z + this.zOffset
    }

    Objects.get(function(objectArray, objectIndex) {
      let i = 0

      self.objectIndex = objectIndex
      self.setObjects(objectArray)
      self.$objects.blobs.tick = self.scene.tick
      self.$objects.sticks.tick = self.scene.tick

      self.scene.add(self.$objects.blobs, self.$objects.sticks)

      var blobs = self.$objects.blobs

      var processBlobs = function(i) {
        var startTime = Date.now()

        for (; Date.now()-startTime < 12 && i < blobs.children.length; i++) {
          var blob = blobs.children[i]
          var obj = blob.objectData
          var c = obj.dateCreated
          var bullet = obj.bullet

          obj.categoryObjects.sort((a, b) => Math.abs(a.dateCreated - c) - Math.abs(b.dateCreated - c))

          for (var j = 0; j < obj.categoryObjects.length; j++) {
            var related = self.blobIndex[obj.categoryObjects[j].bullet]
            if (related && related.objectData.bullet !== bullet) {
              // console.log('related => ', related)
              blob.addConnection(related)
            }
          }
        }

        return i
      };

      var ival = setInterval(function() {
        // console.log(i);
        i = processBlobs(i);
        if (i === blobs.children.length) {
          // console.log('done');
          clearInterval(ival)
          self.loadingPercentageMax += 10
          // console.timeEnd('blobs');
          return
        }
      }, 16)
    })
  }
}

